package cn.bugstack.mybatis.session.defaults;

import cn.bugstack.mybatis.executor.Executor;
import cn.bugstack.mybatis.mapping.Environment;
import cn.bugstack.mybatis.session.Configuration;
import cn.bugstack.mybatis.session.SqlSession;
import cn.bugstack.mybatis.session.SqlSessionFactory;
import cn.bugstack.mybatis.session.TransactionIsolationLevel;
import cn.bugstack.mybatis.transaction.Transaction;
import cn.bugstack.mybatis.transaction.TransactionFactory;

import java.sql.SQLException;

public class DefaultSqlSessionFactory implements SqlSessionFactory {
    private final Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public SqlSession openSqlSession() {
        Transaction tx = null;
        try{
            Environment environment = configuration.getEnvironment();
            TransactionFactory transactionFactory = environment.getTransactionFactory();
            tx = transactionFactory.newTransaction(environment.getDataSource(), TransactionIsolationLevel.READ_COMMITTED, false);
            //创建执行者
            final Executor executor = configuration.newExecutor(tx);
            //创建SqlSession
            return new DefaultSqlSession(configuration, executor);
        }catch (Exception e){
            try{
                assert tx != null;
                tx.close();

            }catch (SQLException ignore){
            }
            throw new RuntimeException("Error  opening session.  Cause: " + e);

        }
    }
}
